package com.tbit.uqbike.client.remote;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 百度地图
 *
 * @author Leon
 * 2015-8-28 下午05:29:38
 */
public class BDHttpClient {
    private final static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    private static HttpClient client = null;

    /**
     * 维持单session
     */
    public static HttpClient getClient() {
        if (client == null) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            client = new HttpClient(connectionManager);
            /**设置编码*/
            client.getParams().setContentCharset("UTF-8");
            /**请求超时*/
            client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
            /**读取超时*/
            client.getHttpConnectionManager().getParams().setSoTimeout(5000);
        }
        return client;
    }

    /**
     * 查询地址
     */
    public static String getAddress(Float lo, Float ln) {
        HttpClient client = getClient();
        GetMethod get = null;
        String address = null;
        try {
            get = new GetMethod("http://api.map.baidu.com/geocoder/v2/?output=json&ak=FklcbdilEe245AtwVev5yASsCksbs5AZ&location=" + ln + "," + lo);
            client.executeMethod(get);
            String result = get.getResponseBodyAsString();
            JSONObject object = JSONObject.parseObject(result);
            Integer state = object.getInteger("status");
            if (state == 0) {
                address = object.getJSONObject("result").getString("formatted_address");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            get.releaseConnection();
        }

        log.info(lo + "," + ln + "=" + address);

        return address;
    }

    public static void main(String[] args) {
        System.out.println(getAddress(113.9059F, 22.5596F));
    }
}